import { Entity, Column, BeforeInsert } from 'typeorm';
import { Exclude } from 'class-transformer';
import * as bcrypt from 'bcrypt';
import { BaseEntity } from '../../../common/entities/base.entity';

/**
 * 用户实体
 */
@Entity('users')
export class User extends BaseEntity {
  @Column({ unique: true, length: 50, comment: '用户名' })
  username: string;

  @Column({ unique: true, length: 100, comment: '邮箱' })
  email: string;

  @Exclude()
  @Column({ length: 255, comment: '密码' })
  password: string;

  @Column({ length: 50, nullable: true, comment: '昵称' })
  nickname: string;

  @Column({ type: 'text', nullable: true, comment: '头像' })
  avatar: string;

  @Column({
    type: 'tinyint',
    default: 1,
    comment: '状态：0-禁用，1-启用',
  })
  status: number;

  @Column({
    type: 'varchar',
    length: 20,
    default: 'user',
    comment: '角色：admin-管理员，user-普通用户',
  })
  role: string;

  /**
   * 插入数据前对密码进行加密
   */
  @BeforeInsert()
  async hashPassword() {
    if (this.password) {
      this.password = await bcrypt.hash(this.password, 10);
    }
  }

  /**
   * 验证密码
   */
  async validatePassword(password: string): Promise<boolean> {
    return bcrypt.compare(password, this.password);
  }
}

